import api from './api';
import type { GameInfo, AskQuestionRequest, AnswerResponse, GameRecord, Soup, ApiResponse, CreateRoomRequest, GameRoom, SendMessageRequest } from '../types';

// 游戏服务
const gameService = {
  // 创建新游戏
  createGame: async (soupId: string, difficulty: 'easy' | 'medium' | 'hard' = 'medium'):
    Promise<GameInfo> => {
    const response = await api.post('/games', {
      soupId,
      difficulty
    });
    return response;
  },

  // 获取游戏信息
  getGame: async (gameId: string): Promise<GameInfo> => {
    const response = await api.get(`/games/${gameId}`);
    return response;
  },

  // 提问
  askQuestion: async (gameId: string, data: AskQuestionRequest): Promise<AnswerResponse> => {
    const response = await api.post(`/games/${gameId}/questions`, data);
    return response;
  },

  // 获取游戏提问历史
  getGameHistory: async (gameId: string): Promise<{ questions: string[], answers: string[] }> => {
    const response = await api.get(`/games/${gameId}/history`);
    return response;
  },

  // 使用提示
  useHint: async (gameId: string): Promise<{ hint: string }> => {
    const response = await api.post(`/games/${gameId}/hint`);
    return response;
  },

  // 揭晓汤底
  revealSolution: async (gameId: string): Promise<{ solution: string }> => {
    const response = await api.post(`/games/${gameId}/reveal`);
    return response;
  },

  // 放弃游戏
  abandonGame: async (gameId: string): Promise<void> => {
    await api.post(`/games/${gameId}/abandon`);
  },

  // 完成游戏
  completeGame: async (gameId: string): Promise<{ score: number }> => {
    const response = await api.post(`/games/${gameId}/complete`);
    return response;
  },

  // 获取用户游戏记录
  getUserGameRecords: async (): Promise<GameRecord[]> => {
    const response = await api.get('/users/games');
    return response;
  },

  // 获取推荐的海龟汤
  getRecommendedSoups: async (): Promise<any[]> => {
    const response = await api.get('/soups/recommended');
    return response;
  },

  // 获取热门海龟汤
  getPopularSoups: async (): Promise<any[]> => {
    const response = await api.get('/soups/popular');
    return response;
  },

  // 搜索海龟汤
  searchSoups: async (keyword: string): Promise<any[]> => {
    const response = await api.get('/soups/search', {
      params: { keyword }
    });
    return response;
  },

  // 获取海龟汤题目列表
  getSoupList: async (filters?: { 
    difficulty?: 'easy' | 'medium' | 'hard'; 
    theme?: string; 
    isOfficial?: boolean; 
    page?: number; 
    pageSize?: number 
  }): Promise<ApiResponse<any>> => {
    try {
      const params = new URLSearchParams();
      if (filters) {
        if (filters.difficulty) params.append('difficulty', filters.difficulty);
        if (filters.theme) params.append('theme', filters.theme);
        if (filters.isOfficial !== undefined) params.append('isOfficial', filters.isOfficial.toString());
        if (filters.page) params.append('page', filters.page.toString());
        if (filters.pageSize) params.append('pageSize', filters.pageSize.toString());
      }
      
      const response = await api.get(`/soups?${params.toString()}`);
      return {
        success: true,
        data: response
      };
    } catch (error) {
      console.error('获取题目列表失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '获取题目列表失败'
      };
    }
  },

  // 获取单个海龟汤题目详情
  getSoupDetail: async (soupId: string): Promise<ApiResponse<Soup>> => {
    try {
      const response = await api.get(`/soups/${soupId}`);
      return {
        success: true,
        data: response
      };
    } catch (error) {
      console.error('获取题目详情失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '获取题目详情失败'
      };
    }
  },

  // 创建海龟汤题目
  createSoup: async (soupData: any): Promise<ApiResponse<Soup>> => {
    try {
      const response = await api.post('/soups', soupData);
      return {
        success: true,
        data: response
      };
    } catch (error) {
      console.error('创建题目失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '创建题目失败'
      };
    }
  },

  // 猜测汤底
  guessSolution: async (soupId: string, guess: string): Promise<ApiResponse<{ 
    correct: boolean; 
    solution?: string; 
    score?: number; 
    message?: string 
  }>> => {
    try {
      const response = await api.post(`/soups/${soupId}/guess`, { guess });
      return {
        success: true,
        data: response
      };
    } catch (error) {
      console.error('猜测失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '猜测失败'
      };
    }
  },

  // 开始新游戏
  startGame: async (soupId: string): Promise<ApiResponse<GameRecord>> => {
    try {
      const response = await api.post('/games', { soupId });
      return {
        success: true,
        data: response
      };
    } catch (error) {
      console.error('开始游戏失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '开始游戏失败'
      };
    }
  },

  // 结束游戏
  endGame: async (gameId: string): Promise<ApiResponse<GameRecord>> => {
    try {
      const response = await api.put(`/games/${gameId}/end`);
      return {
        success: true,
        data: response
      };
    } catch (error) {
      console.error('结束游戏失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '结束游戏失败'
      };
    }
  },

  // 获取当前进行中的游戏
  getCurrentGame: async (): Promise<ApiResponse<GameRecord | null>> => {
    try {
      const response = await api.get('/games/current');
      return {
        success: true,
        data: response
      };
    } catch (error) {
      console.error('获取当前游戏失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '获取当前游戏失败'
      };
    }
  },

  // 创建游戏房间
  createGameRoom: async (roomData: CreateRoomRequest): Promise<ApiResponse<GameRoom>> => {
    try {
      const response = await api.post('/rooms', roomData);
      return {
        success: true,
        data: response
      };
    } catch (error) {
      console.error('创建房间失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '创建房间失败'
      };
    }
  },

  // 获取游戏房间列表
  getGameRooms: async (filters?: { 
    status?: 'waiting' | 'playing' | 'closed'; 
    hasPassword?: boolean; 
    page?: number; 
    pageSize?: number 
  }): Promise<ApiResponse<any>> => {
    try {
      const params = new URLSearchParams();
      if (filters) {
        if (filters.status) params.append('status', filters.status);
        if (filters.hasPassword !== undefined) params.append('hasPassword', filters.hasPassword.toString());
        if (filters.page) params.append('page', filters.page.toString());
        if (filters.pageSize) params.append('pageSize', filters.pageSize.toString());
      }
      
      const response = await api.get(`/rooms?${params.toString()}`);
      return {
        success: true,
        data: response
      };
    } catch (error) {
      console.error('获取房间列表失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '获取房间列表失败'
      };
    }
  },

  // 获取房间详情
  getGameRoomDetail: async (roomId: string): Promise<ApiResponse<GameRoom>> => {
    try {
      const response = await api.get(`/rooms/${roomId}`);
      return {
        success: true,
        data: response
      };
    } catch (error) {
      console.error('获取房间详情失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '获取房间详情失败'
      };
    }
  },

  // 加入房间
  joinGameRoom: async (roomId: string, password?: string): Promise<ApiResponse<GameRoom>> => {
    try {
      const response = await api.post(`/rooms/${roomId}/join`, { password });
      return {
        success: true,
        data: response
      };
    } catch (error) {
      console.error('加入房间失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '加入房间失败'
      };
    }
  },

  // 离开房间
  leaveGameRoom: async (roomId: string): Promise<ApiResponse<{ message: string }>> => {
    try {
      const response = await api.post(`/rooms/${roomId}/leave`);
      return {
        success: true,
        data: { message: response.message || '已成功离开房间' }
      };
    } catch (error) {
      console.error('离开房间失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '离开房间失败'
      };
    }
  },

  // 发送房间消息
  sendRoomMessage: async (messageData: SendMessageRequest): Promise<ApiResponse<any>> => {
    try {
      const response = await api.post('/messages/room', messageData);
      return {
        success: true,
        data: response
      };
    } catch (error) {
      console.error('发送消息失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '发送消息失败'
      };
    }
  },

  // 发送私聊消息
  sendPrivateMessage: async (messageData: SendMessageRequest): Promise<ApiResponse<any>> => {
    try {
      const response = await api.post('/messages/private', messageData);
      return {
        success: true,
        data: response
      };
    } catch (error) {
      console.error('发送私聊消息失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '发送私聊消息失败'
      };
    }
  },

  // 获取房间消息历史
  getRoomMessages: async (roomId: string, limit: number = 50, before?: string): Promise<ApiResponse<any[]>> => {
    try {
      const params = new URLSearchParams({ limit: limit.toString() });
      if (before) params.append('before', before);
      
      const response = await api.get(`/messages/room/${roomId}?${params.toString()}`);
      return {
        success: true,
        data: response
      };
    } catch (error) {
      console.error('获取房间消息历史失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '获取房间消息历史失败'
      };
    }
  },

  // 获取私聊消息历史
  getPrivateMessages: async (userId: string, limit: number = 50, before?: string): Promise<ApiResponse<any[]>> => {
    try {
      const params = new URLSearchParams({ limit: limit.toString() });
      if (before) params.append('before', before);
      
      const response = await api.get(`/messages/private/${userId}?${params.toString()}`);
      return {
        success: true,
        data: response
      };
    } catch (error) {
      console.error('获取私聊消息历史失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '获取私聊消息历史失败'
      };
    }
  },

  // 获取聊天会话列表
  getChatSessions: async (type?: 'rooms' | 'private'): Promise<ApiResponse<any[]>> => {
    try {
      const endpoint = type ? `/messages/sessions?type=${type}` : '/messages/sessions';
      const response = await api.get(endpoint);
      return {
        success: true,
        data: response
      };
    } catch (error) {
      console.error('获取聊天会话列表失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '获取聊天会话列表失败'
      };
    }
  },

  // 搜索用户
  searchUsers: async (query: string): Promise<ApiResponse<any[]>> => {
    try {
      const response = await api.get(`/users/search?q=${encodeURIComponent(query)}`);
      return {
        success: true,
        data: response
      };
    } catch (error) {
      console.error('搜索用户失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '搜索用户失败'
      };
    }
  }
};

export default gameService;